<template>
	<div>
		<!-- 面包屑导航 -->
		<el-breadcrumb separator-class="el-icon-arrow-right">
		  <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
		  <el-breadcrumb-item>用户管理</el-breadcrumb-item>
		  <el-breadcrumb-item :to="{ path: '/users' }">用户列表</el-breadcrumb-item>
		  
		</el-breadcrumb>
		<!-- 卡片视图 -->
		<el-card class="box-card">  
		     <!-- gutter  le-col之间距离 -->
					<el-row :gutter="20">
					  <el-col :span="12">
							<el-input placeholder="请输入内容" v-model="queryInfo.query" clearable @clear="getUserList">
		          <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
		      </el-input>
					</el-col>
					  <el-col :span="4"> 
						  <el-button type="primary" @click="changeAddDialogVisible" v-model="addForm.username">添加用户</el-button>
						</el-col>
					  
					</el-row>
		 <el-table
		       border stripe
		      :data="userList"
		      style="width: 100%">
					<el-table-column type="index" label="#">
						
					</el-table-column>
		      <el-table-column
		        prop="username"
		        label="姓名"
		        width="180">
		      </el-table-column>
		      <el-table-column
		        prop="email"
		        label="邮箱"
		        width="180">
		      </el-table-column>
		      <el-table-column
		        prop="mobile"
		        label="电话">
		      </el-table-column>
					<el-table-column
					  prop="role_name"
					  label="角色">
					</el-table-column>
					<el-table-column
					  prop="mg-state"
					  label="状态">
							<template v-slot="scope">
							<el-switch v-model="scope.row.mg_state" @change="userStateChange(scope.row)">
							</el-switch>
							</template>
					</el-table-column>
					<el-table-column label="操作" width="180px">
					    <template v-slot="scope">
								<!-- 修改按钮 -->
								<el-button type="primary" icon="el-icon-edit" size="mini" 
								@click="showEditDialog(scope.row.id)"></el-button>
								<!-- 删除按钮 -->
								<el-button type="danger" icon="el-icon-delete" size="mini" @click="removeUserById(scope.row.id)"></el-button>
								<!-- 分配角色按钮 -->
								 <el-tooltip  effect="dark" content="分配角色" placement="top" :enterable='false'>
								      <el-button type="warning" icon="el-icon-setting" size="mini"
											@click="setRole(scope.row)"></el-button>
								 </el-tooltip>
								
							</template>
					</el-table-column>
		    </el-table>
				<!-- 分页区 -->
		<el-pagination
		     @size-change="handleSizeChange"
		     @current-change="handleCurrentChange"
		     :current-page="queryInfo.pagenum"
		     :page-sizes="[1, 2, 5, 10]"
		     :page-size="queryInfo.pagesize"
				  
		     layout="total, sizes, prev, pager, next, jumper"
		     :total="Total">
		   </el-pagination>
		</el-card>
		<!-- 添加用户的对话框 -->
		<el-dialog
		  title="添加用户"
		  :visible.sync="addDialogVisible"
		  width="50%" @close="addDialogClose">
		  <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="70px">
		    <el-form-item label="用户名" prop="username">
		      <el-input v-model="addForm.username"></el-input>
		    </el-form-item>
				<el-form-item label="密码" prop="password">
				  <el-input v-model="addForm.password"></el-input>
				</el-form-item>
				<el-form-item label="邮箱" prop="email">
				  <el-input v-model="addForm.email"></el-input>
				</el-form-item>
				<el-form-item label="手机" prop="telephone">
				  <el-input v-model="addForm.telephone"></el-input>
				</el-form-item>
			</el-form>
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="addDialogVisible = false">取 消</el-button>
		    <el-button type="primary" @click="adduser">确 定</el-button>
		  </span>
		</el-dialog>
		<!-- 修改用户的对话框 -->
    <el-dialog
      title="修改用户"
      :visible.sync="EditDialogVisible"
      width="50%" @close="edDialogClosed">
			<el-form :model="editForm" :rules="editFormRules" ref="editFormRef" label-width="70px">
			  <el-form-item label="用户名" >
			    <el-input v-model="editForm.username" disabled></el-input>
			  </el-form-item>
				<!--prop是校验的属性名 对应 editFormRules: email -->
				<el-form-item label="邮箱" prop="email">
				  <el-input v-model="editForm.email"></el-input>
				</el-form-item>
				
				<el-form-item label="电话" prop="mobile">
				  <el-input v-model="editForm.mobile"></el-input>
				</el-form-item>
			</el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="EditDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="editUser">确 定</el-button>
      </span>
    </el-dialog>
		<!-- 分配角色的对话框 -->
		<el-dialog
		  title="分配角色"
		  :visible.sync="setRoleVisible"
		  width="50%" @close="setRoleDialogClose">
		  <div>
				<p>当前的用户:{{userInfo.username}}</p>
				<p>当前的角色:{{userInfo.role_name}}</p>
				<p>分配新角色:<el-select v-model="selectedRoleId" placeholder="请选择">
    <el-option
      v-for="item in roleList"
      :key="item.id"
      :label="item.roleName"
      :value="item.id">
    </el-option>
  </el-select></p>
			</div>
		  <span slot="footer" class="dialog-footer">
		    <el-button @click="setRoleVisible = false">取 消</el-button>
		    <el-button type="primary" @click="saveRoleInfo">确 定</el-button>
		  </span>
		</el-dialog>
	</div>
</template>

<script>
	export default{
		data(){
			var checkEmail=(rule,value,callback)=>{
				//验证邮箱
				const regEmail=/^[a-zA-Z0-9]+@[a-zA-Z0-9]+(\.com|.cn)+$/
				//value是输入的值
				if(regEmail.test(value)){
					return callback()
				}
				callback(new Error('邮箱格式错误'))
			}
			var checkTel=(rule,value,callback)=>{
				const regTel=/^\d{11}$/
				if(regTel.test(value)){
					return callback()
				}
				callback(new Error('手机格式错误'))
			}
			return{
				//已选中的角色Id值
				selectedRoleId:'',
				//获取用户列表参数
				queryInfo:{
					query:'',
					pagenum:1,
					pagesize:2
				},
				//控制分配角色的对话框
				setRoleVisible:false,
				userList:[],
				Total:0,
				//控制对话框的显示与隐藏
				addDialogVisible:false,
				//控制编辑的对话框显示
				EditDialogVisible:false,
				//查询到的用户信息对象
				editForm:{},
				editFormRules:{
					email:[
						{validator: checkEmail,trigger:'blur'}
					],
					mobile:[
						{validator: checkTel,trigger:'blur'}
					]
				},
				//添加用户
				addForm:{
					username:'',
					password:'',
					email:'',
					telephone:''
				},
					//添加表单的验证规则对象
				addFormRules:{
					username:[
						{required:true,message:'请输入用户名',trigger:'blur'},
						{max:10,min:3,message:'用户名的长度再3到10个字符之间',trigger:'blur'}
					],
					password:[
						{required:true,message:'请输入密码',trigger:'blur'},
						{max:10,min:3,message:'用户名的长度再3到10个字符之间',trigger:'blur'}
					],
					email:[
						{validator: checkEmail,trigger:'blur'}
					],
					telephone:[
					{validator: checkTel,trigger:'blur'}
					]
				},
				//需要被分配角色 的用户信息
				userInfo:{},
				roleList:[]
				
			}
		},
		created() {
			this.getUserList()
		},
		methods:{
			//监听分配角色对话框关闭事件
			setRoleDialogClose(){
				this.selectedRoleId=''
				this.userInfo={}
			},
			//点击按钮分配角色
		async	saveRoleInfo(){
			console.log(this.selectedRoleId)
			if(!this.selectedRoleId) return this.$message.info('请选择分配的角色')
		const {data:res}=await	this.$http.put(`users/${this.userInfo.id}/role`,{rid:this.selectedRoleId})
		console.log(this.userInfo)
		if(res.meta.status!==200) return this.$message.info('分配角色失败')
		console.log(this.roleList)
		this.getUserList()
		this.setRoleVisible=false
		return this.$message.success('分配角色成功')
		
		},
			//展示分配角色的对话框
		async	setRole(userInfo){
				this.userInfo=userInfo
				//获取角色列表
		const {data:res}=await this.$http.get('roles')
		if(res.meta.status!==200) return this.$message.error('获取角色列表失败')
		this.roleList=res.data
				this.setRoleVisible=true
				
			},
			//展示编辑用户的对话框
			showEditDialog(value){
				console.log(value)
				this.EditDialogVisible=!this.EditDialogVisible;
				this.$http.get('users/'+value).then(res=>{
					if(res.data.meta.status!=200){
						return this.$message.error('查询失败')
					}
					console.log(res)
					this.editForm=res.data.data
					console.log(this.editForm)
				})
			},
			//点击按钮添加新用户
			adduser(){
				this.$refs.addFormRef.validate(valid=>{
					if(!valid) return;
					//可以发起添加用户的网络请求
					this.$http.post('users',{username:this.addForm.username,password:this.addForm.password,
					email:this.addForm.email,mobile:this.addForm.telephone}).then(res=>{
						if(res.data.meta.status!=201){
							this.$message.error('添加失败')
						}
						this.$message.success('添加成功')
						//隐藏添加用户的对话框
						this.addDialogVisible=false;
						//重新获取列表数据
						this.getUserList()
					})
				})
			},
			//编辑用户
			editUser(){
				this.$refs.editFormRef.validate(valid=>{
					if(!valid) return;
					console.log(this.editForm)
					this.$http.put('users/'+this.editForm.id,{email:this.editForm.email,
					mobile:this.editForm.mobile}).then(res=>{
						console.log(res)
						if(res.data.meta.status!==200){
							return this.$message.error('编辑失败')
						}
					   this.$message.success('编辑成功')
					})
					this.EditDialogVisible = false
					this.getUserList()
				})
				
			},
			//监听添加对话框的关闭事件
			addDialogClose(){
				this.$refs.addFormRef.resetFields()
			},
				changeAddDialogVisible(){
					this.addDialogVisible=true
				},
			getUserList(){
				this.$http.get('users',{params:this.queryInfo}).then(res=>{
					console.log(res)
					if(res.data.meta.status!=200) return this.$message.error('获取失败');
					this.userList=res.data.data.users;
					this.Total=res.data.data.total;
					
				})
			},
			// 监听pagesize改变的事件
			handleSizeChange(newSize){
				console.log(newSize)
				this.queryInfo.pagesize=newSize
				this.getUserList()
			},
			// 监听页码值改变的事件
			handleCurrentChange(newPage){
				this.queryInfo.pagenum=newPage
				this.getUserList()
				
			},
			//根据Id删除对应的用户信息
			async removeUserById(id){
				//询问用户是否删除数据
		const confirmResult=	await this.$confirm('是否删除用户数据', '提示', {
				          confirmButtonText: '确定',
				          cancelButtonText: '取消',
				          type: 'warning',
				          center: true
				        }).catch(err=>{
									return err
								})
								// 如果用户取消删除 则返回值为字符串cancel
								//如果用户确认删除，则返回值为字符串confirm
								if(confirmResult!=='confirm') return this.$message.info('以取消删除')
								// return this.$message.success("删除成功")
								const {data:res}=await this.$http.delete('users/'+id)
								if(res.meta.status!==200) return this.$message.error('删除失败')
								this.$message.success('删除成功')
								this.getUserList()
			},
			// 监听switch的开关状态改变
			userStateChange(userInfo){
				console.log(userInfo.id)
				this.$http.put(`users/${userInfo.id}/state/${userInfo.mg_state}`).then(res=>{
					console.log(res)
					if(res.data.meta.status!==200){
						userInfo.mg_state=!userInfo.mg_state
						return this.$message.error('更新用户状态失败')
					}
					this.$message.success('更新用户状态成功')
				})
			},
			edDialogClosed(){
				this.$refs.editFormRef.resetFields()
			}
		}
	}
</script>

<style>
</style>
